﻿package code
{
	import flash.utils.Timer;
	import flash.events.TimerEvent;
	
	public class EnemyWeapon extends GenericWeapon
	{
		// Timer used for bullet firing spacing
		protected var firingTimer:Timer;
		// Timer used for cooldown
		protected var cooldownTimer:Timer;
		
		// Returns the enemy to which this weapon is attached
		protected function get EnemyObj():GenericEnemy { return parent as GenericEnemy; }

		public function EnemyWeapon(spawnX:int, spawnY:int, bulletsTilCooldown:int, fireTimerDelay:int, cooldownTimerDelay:int, bulletType:Class)
		{
			super(spawnX, spawnY, bulletType);
			
			firingTimer = new Timer(fireTimerDelay, bulletsTilCooldown);
			firingTimer.addEventListener(TimerEvent.TIMER, fire);
			firingTimer.addEventListener(TimerEvent.TIMER_COMPLETE, startCooldown);
			
			cooldownTimer = new Timer(cooldownTimerDelay, 1);
			cooldownTimer.addEventListener(TimerEvent.TIMER_COMPLETE, endCooldown);
		}
		
		public function trigger()
		{
			firingTimer.start();
		}
	
		private function fire(e:TimerEvent)
		{
			var b:GenericBullet = super.fireBullet(0, 7);
			
			EnemyObj.CurrentLevel.addEnemyBullet(b);
		}
		
		private function startCooldown(e:TimerEvent)
		{
			cooldownTimer.reset();
			cooldownTimer.start();
		}
		
		private function endCooldown(e:TimerEvent)
		{
			firingTimer.reset();
			firingTimer.start();
		}
		
		public function cleanup()
		{
			firingTimer.removeEventListener(TimerEvent.TIMER, fire);
			firingTimer.removeEventListener(TimerEvent.TIMER_COMPLETE, startCooldown);
			cooldownTimer.removeEventListener(TimerEvent.TIMER_COMPLETE, endCooldown);
			
			firingTimer.stop();
			cooldownTimer.stop();
			firingTimer = null;
			cooldownTimer = null;
		}
	}
}